package com.xxh.kfc.controller;



import com.xxh.kfc.dao.UserDao;
import com.xxh.kfc.entity.User;
import com.xxh.kfc.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


//设置访问路径
@WebServlet(urlPatterns = "/user/*")
public class UserServlet extends HttpServlet {

SqlSession sqlSession = MyBatisUtils.getSqlSession();

    //处理get请求（浏览器请求，超链接，转发，重定向）
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理登录请求
        String pathInfo = req.getPathInfo();
        UserDao userDao = sqlSession.getMapper(UserDao.class);

        // 1 登录请求
        if (pathInfo.equals("/login")) {
            //登录请求
            //请求处理
            String username = req.getParameter("username");
            String password = req.getParameter("password");

            System.out.println("username=" + username + "password:" + password);
            User user = userDao.login(username, password);
            if (user != null) {
                HttpSession session = req.getSession();
                session.setAttribute("userDetail", user);

                //跳转到食物的controller
                resp.sendRedirect(req.getContextPath() + "/main.jsp");

            } else {
                //重定向到登录页
                //req.getContextPath()获取web项目访问路径
                resp.sendRedirect(req.getContextPath() + "/login.jsp?info=1");
            }
        }
        //2 退出登录
        if(pathInfo.equals("/logout")){
            HttpSession session = req.getSession();
            session.invalidate();
            resp.sendRedirect(req.getContextPath()+"/login.jsp?info=1");
        }
    }

    //处理post请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
